package com.xywy.start;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.constants.ConstantValue;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.MLog;
import com.xywy.common.util.StringUtils;
import com.xywy.common.widget.MyDialog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.me.SetupAcPwdActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.PasswordAuthentication;
import java.util.HashMap;

/**
 * 验证码：(1)注册- 密码确认 (2)登录 - 验证码登录 - 验证码确认 (3)登录 - 忘记密码 － 验证码确认
 * 
 * @author xiaogd
 * 
 */
public class ValidateCodeActivity extends BaseActivity implements
		OnClickListener {
	private static final String TAG = "ValidateCodeActivity";
	private int target;
	private Button btnNext;
	private TextView valTs;
	private TextView tvMObile;
	JSONObject msgBack;
	MyProgress myProgress;
	// EditText val_pwd;
	String phonenum;
	String id;
	String accountstr;
	private TextView timer;
	private Context mContext;
	private MyTimer mc;
	private TextView newGet;
	int sex;
	int height;
	String birthday;
	String password;
	private EditText val_code;
	private String authcode;
	private Button back;
	private TextView tvBack;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.start_validate_code);
		this.preInit();
		this.initView();
		this.loadData();

	}

	public void startOnClick(View view) {
		switch (view.getId()) {
		case R.id.btn_start_valcode_next:
			if (StringUtils.isNull(val_code.getText().toString())) {
				Toast.makeText(mContext, "请填写六位验证码", Toast.LENGTH_SHORT).show();
				return;
			}

			registerNext();
			newGetCode = false;
			break;
		case R.id.tv_val_pwd_timer_newget:
			final MyDialog dialog = new MyDialog(this, R.style.MyDialogStyle);
			dialog.show();
			dialog.setContentView(R.layout.mydialog_twobutton_layout);
			TextView mydialog_twobutton_layout_content_textView = (TextView) dialog
					.findViewById(R.id.mydialog_twobutton_layout_content_textView);
			mydialog_twobutton_layout_content_textView.setText("收不到验证码？");
			TextView leftButton = (TextView) dialog
					.findViewById(R.id.mydialog_twobutton_layout_left_button);
			leftButton.setText("取消");

			TextView rightButton = (TextView) dialog
					.findViewById(R.id.mydialog_twobutton_layout_right_button);
			rightButton.setText("重新发送");
			dialog.findViewById(R.id.mydialog_twobutton_layout_left_button)
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.dismiss();
							finish();
						}
					});
			dialog.findViewById(R.id.mydialog_twobutton_layout_right_button)
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							mc.start();
							// 是否是当前页重新获取验证码
							newGetCode = true;
							sendMsg();
						}
					});

			break;

		}
		;
	}

	private void registerNext() {
		// 发送网络请求
		this.sendMsg();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.register_pwd_title_bar);
		TextView tvTitle = titleBar.getTitle();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		// titleBar.onClickBack(this);

		// back = titleBar.getBtnBack();
		// back.setOnClickListener(this);
		tvBack = titleBar.getTvBack();
		tvBack.setOnClickListener(this);
		btnNext = (Button) findViewById(R.id.btn_start_valcode_next);
		valTs = (TextView) findViewById(R.id.tv_start_valcode_ts);

		tvMObile = (TextView) findViewById(R.id.tv_start_valpwd_number);
		String kg = "    ";
		tvMObile.setText(phonenum.substring(0, 3) + kg
				+ phonenum.substring(3, 7) + kg + phonenum.substring(7, 11));

		val_code = (EditText) findViewById(R.id.et_val_code);
		timer = (TextView) findViewById(R.id.tv_val_pwd_timer);
		newGet = (TextView) findViewById(R.id.tv_val_pwd_timer_newget);

		String title = "";
		String next = "";
		if (target == ConstantValue.REGISTERVAL) { // 注册
			title = getString(R.string.tv_start_btnregister);

			next = getString(R.string.tv_start_register_str);
			val_code.setHint(getString(R.string.et_start_valpwd_hint));
			String ts = getString(R.string.tv_start_valpwd_ts_reg);
			// 控件赋值
			Spannable span = new SpannableString(ts);
			span.setSpan(new ForegroundColorSpan(mContext.getResources()
					.getColor(R.color.start_bt_bg)), 6, 9,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			valTs.setText(span);

		} else if (target == ConstantValue.VALLOGIN) { // 验证码登陆
			title = getString(R.string.tv_start_valcode_qr);
			next = getString(R.string.et_start_btn_login);
			val_code.setHint(getString(R.string.et_start_valcode_hint));
			String ts = getString(R.string.tv_start_valpwd_ts);
			// 控件赋值
			Spannable span = new SpannableString(ts);
			span.setSpan(new ForegroundColorSpan(mContext.getResources()
					.getColor(R.color.start_bt_bg)), 6, 9,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			valTs.setText(span);
		} else if (target == ConstantValue.CHANGEPWD) { // 忘记密码
			title = getString(R.string.tv_start_valcode_qr);
			next = getString(R.string.me_setup_account_szxmm);
			val_code.setHint(getString(R.string.et_start_valcode_hint));
			String ts = getString(R.string.tv_start_valpwd_ts);
			// 控件赋值
			Spannable span = new SpannableString(ts);
			span.setSpan(new ForegroundColorSpan(mContext.getResources()
					.getColor(R.color.start_bt_bg)), 6, 9,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			valTs.setText(span);
		}
		tvTitle.setText(title);
		btnNext.setText(next);

		myProgress = new MyProgress(this, 10);

		// 启动倒计时
		mc = new MyTimer(60000, 1000);
		mc.start();
	}

	@Override
	public void preInit() {
		this.mContext = this.context;
		target = getIntent().getIntExtra("target", 0);

		if (target == ConstantValue.REGISTERVAL) { // 注册
			phonenum = getIntent().getStringExtra("mobile"); // 手机号
			accountstr = getIntent().getStringExtra("account"); // 主用户昵称
			sex = getIntent().getIntExtra("sex", 1); // 性别，男1女2
			height = getIntent().getIntExtra("height", 0); // 身高cm
			birthday = getIntent().getStringExtra("birthday"); // 生日，时间戳
			password = getIntent().getStringExtra("password");// 手动输入的密码
			id = getIntent().getStringExtra("id");
			// authcode = val_code.getText().toString().trim();
		} else if (target == ConstantValue.VALLOGIN) { // 验证码登陆
			phonenum = getIntent().getStringExtra("mobile"); // 手机号

		} else if (target == ConstantValue.CHANGEPWD) { // 忘记密码
			phonenum = getIntent().getStringExtra("mobile"); // 手机号
			id = getIntent().getStringExtra("id");
		}

	}

	@Override
	public void loadData() {

	}

	String userid = "";
	int resultCode;
	int state;
	String errorInfo;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			if (msg.obj == null) {
				myProgress.stop();
				return;
			}

			myProgress.stop();
			try {
				msgBack = new JSONObject(msg.obj.toString());
				resultCode = msgBack.optInt("code");
				state = msgBack.optInt("state");
				errorInfo = msgBack.optString("error");
				JSONObject data = msgBack.optJSONObject("data");
				if (null != data) {
					userid = data.optString("userid");
					// phonenum = data.optString("phonenum");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if ((resultCode == ResultCode.SUCCESSCODE) || (state == 200)) {
				if (newGetCode) { // 是否为当前页重新获取 验证码
					newGetCode = false;
					Log.e(TAG + "》》》》》》》》》》》》》》》》", "超时啦！！！！！！！！");
					return;
				} else {
					System.out.println("非验证码登陆时候的值  " + target);
					if (target == ConstantValue.REGISTERVAL
							|| target == ConstantValue.VALLOGIN) { // 注册 、验证码登陆
						// 将 userid 存入本地
						System.out.println("非验证码登陆时候的值  " + target);
						saveUserid();
						Intent intent = new Intent(mContext,
								FragmentMainActivity.class);
						mContext.startActivity(intent);
						ValidateCodeActivity.this.finish();

					} else if (target == ConstantValue.CHANGEPWD) { // 忘记密码,设置新密码

						// 将userId添加到本地
						saveUserid();

						Intent intent = new Intent(mContext,
								SetupAcPwdActivity.class);
						intent.putExtra("target", ConstantValue.CHANGEPWD);
						intent.putExtra("userid", userid);
						intent.putExtra("phonenum", phonenum);
						intent.putExtra("code", val_code.toString());
						intent.putExtra("id", id);
						startActivity(intent);
						finish();
					}
				}
			} else {
				Toast.makeText(mContext, errorInfo, Toast.LENGTH_SHORT).show();
				if (newGetCode) { // 是否为当前页重新获取 验证码
					newGetCode = false;
				}
				return;
			}
		}
	};

	/**
	 * 将 userid 存入本地
	 */
	private void saveUserid() {
		if (userid == null || "".equals(userid))
			userid = msgBack.optString("userid");
		MLog.i(TAG, "当前人的userid:" + userid);
		SharedPreferences sp = mContext.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("userid", userid);
		editor.putString("mobile", phonenum);
		editor.putString("password", password);
		editor.commit();
	}

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;
	// 是否是当前页重新获取验证码
	private boolean newGetCode = false;

	// 处理网络请求
	public void sendMsg() {
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 是否是当前页超过 60秒, 重新获取验证码
		if (newGetCode) {
			// 请求路径
			paramsParser.action = getString(R.string.validate_sendCode);
			// 请求方式
			paramsParser.request = "get";

			// 请求参数
			params.put("target", phonenum);
			params.put("type", target);
			// 重新发送后的界面

			timer.setText(60 + "");
			findViewById(R.id.ll_start_valpwd_three)
					.setVisibility(View.VISIBLE);
			newGet.setVisibility(View.GONE);
			// timer.setTextColor(getResources().getColor(
			// R.color.wjk_xsdf_share_btn));
			timer.setClickable(false);
			timer.setFocusable(false);

		} else {
			if (target == ConstantValue.REGISTERVAL) { // 注册
				// 请求路径 // verifyCode
				paramsParser.action = getString(R.string.register_user_pwd_verify);
				// 请求方式
				paramsParser.request = "post";
				// 请求参数
				params.put("phonenum", phonenum);
				params.put("accountstr", accountstr);
				// params.put("password", val_pwd.getText().toString());
				params.put("password", password);
				params.put("sex", sex);
				params.put("id", id);
				params.put("height", height);
				params.put("birthday", birthday);
				params.put("code", val_code.getText().toString());

			} else if (target == ConstantValue.VALLOGIN
					|| target == ConstantValue.CHANGEPWD) { // 验证码登陆
				// 请求路径
				paramsParser.action = getString(R.string.verifyCode);
				// 请求方式
				paramsParser.request = "get";

				// 请求参数
				params.put("target", phonenum);
				params.put("id", id);
				params.put("code", val_code.getText().toString());
				params.put("type", ConstantValue.VALLOGIN);
			}
		}
		MLog.i(TAG, params.toString());
		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
	};

	/**
	 * 定义一个倒计时的内部类
	 */
	class MyTimer extends CountDownTimer {
		public MyTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			timer.setText(60 + "");
			findViewById(R.id.ll_start_valpwd_three).setVisibility(View.GONE);
			newGet.setVisibility(View.VISIBLE);
			timer.setTextColor(getResources().getColor(
					R.color.wjk_xsdf_share_btn));
			timer.setClickable(true);
			timer.setFocusable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			timer.setText(millisUntilFinished / 1000 + "");
			timer.setTextColor(getResources().getColor(
					R.color.wjk_xsdf_share_btn_ap));
			timer.setClickable(false);
			timer.setFocusable(false);
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub

		switch (view.getId()) {
		case R.id.tv_title_back:
			showCancelDialog();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showCancelDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showCancelDialog() {
		// TODO Auto-generated method stub
		final MyDialog myDialog = new MyDialog(this, R.style.MyDialogStyle);
		myDialog.show();
		myDialog.setContentView(R.layout.mydialog_twobutton_layout);
		TextView mydialog_twobutton_layout_content_textView = (TextView) myDialog
				.findViewById(R.id.mydialog_twobutton_layout_content_textView);
		mydialog_twobutton_layout_content_textView
				.setText("短信发送可能略有延迟，确定返回并重新开始");
		TextView leftButton = (TextView) myDialog
				.findViewById(R.id.mydialog_twobutton_layout_left_button);
		leftButton.setText("等待");

		TextView rightButton = (TextView) myDialog
				.findViewById(R.id.mydialog_twobutton_layout_right_button);
		rightButton.setText("返回");
		myDialog.findViewById(R.id.mydialog_twobutton_layout_left_button)
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

						myDialog.dismiss();
					}
				});
		myDialog.findViewById(R.id.mydialog_twobutton_layout_right_button)
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						finish();
					}
				});

	}

}
